package com.lizk.net.http.tools;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class PostFile {
	public static String post(String url, Map<String,File> files) throws Exception {

		
		
		CloseableHttpClient  client = HttpClients.createDefault();

		HttpEntity entity = null;

		HttpPost post = new HttpPost(url);
		
		if(files != null && files.size() >= 1) {
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			
			for(Entry<String, File> entry : files.entrySet()) {
				builder.addBinaryBody(entry.getKey(), entry.getValue());
			}
			entity = builder.build();
			post.setEntity(entity);
		}
		
		try {
			HttpResponse response = client.execute(post);
			HttpEntity resultEntity = response.getEntity();
			return EntityUtils.toString(resultEntity, "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("访问网页失败", e);
		}

	}
}
